package 链表;

import java.util.List;

// https://leetcode-cn.com/problems/reverse-linked-list/
public class _206_反转链表 {

    // 1. 递归
    public static ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode newHead = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    // 2. 迭代 一个个取出
    public static ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    // 3. 虚拟头结点
    public static ListNode reverseList3(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode dynamicNode = new ListNode(-1);
        while (head != null) {
            ListNode tmp = head;
            head = head.next;
            tmp.next = dynamicNode.next;
            dynamicNode.next = tmp;
        }
        return dynamicNode.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(5);
        head.next = new ListNode(4);
        head.next.next = new ListNode(9);
        head.next.next.next = new ListNode(1);
        System.out.println(head);
        head = reverseList3(head);
        System.out.println(head);
    }
}
